package com.example.testapplication.ui.userdata;

import androidx.lifecycle.Observer;

import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.example.testapplication.R;
import com.example.testapplication.databinding.ActivityUserDataBinding;
import com.example.testapplication.dialog.AddressDialog;
import com.example.testapplication.dialog.InputDialog;
import com.example.testapplication.event.Event;
import com.example.testapplication.other.FileContentResolver;
import com.example.testapplication.ui.imageselect.ImageCropActivity;
import com.example.testapplication.ui.imageselect.ImageSelectActivity;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnImageViewerLongPressListener;
import com.lxj.xpopup.util.SmartGlideImageLoader;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.BR;


public class UserDataActivity extends BaseActivity<ActivityUserDataBinding,UserDataVewModel> {

    /** 省 */
    private String mProvince = "江西省";
    /** 市 */
    private String mCity = "赣州市";
    /** 区 */
    private String mArea = "章贡区";


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_user_data;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initViewObservable() {
        viewModel.uc.pClickEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                switch (integer){
                    case 1://头像
                        if(TextUtils.isEmpty(viewModel.avatar.get())){
                            ImageSelectActivity.start(UserDataActivity.this, data -> {
                                // 裁剪头像
                                cropImageFile(new File(data.get(0)));
                            });
                        }else {
                            new XPopup.Builder(UserDataActivity.this)
                                    .isDestroyOnDismiss(true)
                                    .asImageViewer(binding.ivPersonDataAvatar, viewModel.avatar.get(), true, Color.parseColor("#f1f1f1"), -1, 0
                                            , false, Color.BLACK, new SmartGlideImageLoader(R.mipmap.ic_launcher), new OnImageViewerLongPressListener() {
                                                @Override
                                                public void onLongPressed(BasePopupView popupView, int position) {
                                                    ToastUtils.showShort("长按了第" + position +"个图片", Toast.LENGTH_SHORT);
                                                }
                                            })
                                    .show();
                        }
                        break;
                    case 2://选择头像
                        ImageSelectActivity.start(UserDataActivity.this, data -> {
                            // 裁剪头像
                            cropImageFile(new File(data.get(0)));
                        });
                        break;
                    case 3://昵称
                        new InputDialog.Builder(UserDataActivity.this)
                                // 标题可以不用填写
                                .setTitle(getString(R.string.personal_data_name_hint))
                                .setContent(binding.sbPersonDataName.getRightText())
                                .setHint(getString(R.string.personal_data_name_hint))
                                //.setConfirm("确定")
                                // 设置 null 表示不显示取消按钮
                                //.setCancel("取消")
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setListener((dialog, content) -> {
                                    if (!binding.sbPersonDataName.getRightText().equals(content)) {
                                        binding.sbPersonDataName.setRightText(content);
                                    }
                                })
                                .show();
                        break;
                    case 4://地址
                        new AddressDialog.Builder(UserDataActivity.this)
                                //.setTitle("选择地区")
                                // 设置默认省份
                                .setProvince(mProvince)
                                // 设置默认城市（必须要先设置默认省份）
                                .setCity(mCity)
                                // 不选择县级区域
                                //.setIgnoreArea()
                                .setListener((dialog, province, city, area) -> {
                                    String address = province + city + area;
                                    if (!binding.sbPersonDataAddress.getRightText().equals(address)) {
                                        mProvince = province;
                                        mCity = city;
                                        mArea = area;
                                        binding.sbPersonDataAddress.setRightText(address);
                                    }
                                })
                                .show();
                        break;
                }
            }
        });
    }


    /**
     * 裁剪图片
     */
    private void cropImageFile(File sourceFile) {
        ImageCropActivity.start(this, sourceFile, 1, 1, new ImageCropActivity.OnCropListener() {

            @Override
            public void onSucceed(Uri fileUri, String fileName) {
                File outputFile;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    outputFile = new FileContentResolver(getApplicationContext(), fileUri, fileName);
                } else {
                    try {
                        outputFile = new File(new URI(fileUri.toString()));
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                        outputFile = new File(fileUri.toString());
                    }
                }
                updateCropImage(outputFile, true);
            }

            @Override
            public void onError(String details) {
                // 没有的话就不裁剪，直接上传原图片
                // 但是这种情况极其少见，可以忽略不计
                updateCropImage(sourceFile, false);
            }
        });
    }


    /**
     * 上传裁剪后的图片
     */
    private void updateCropImage(File file, boolean deleteFile) {
        if (true) {
            if (file instanceof FileContentResolver) {
                viewModel.avatar.set(((FileContentResolver) file).getContentUri().toString());
                RxBus.getDefault().post(new Event(((FileContentResolver) file).getContentUri().toString()));
            } else {
                viewModel.avatar .set(Uri.fromFile(file).toString());
                RxBus.getDefault().post(new Event(Uri.fromFile(file).toString()));
            }

//            Glide.with(getApplicationContext())
//                    .load(mAvatarUrl)
//                    .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
//                    .into(mAvatarView);
            return;
        }

//        EasyHttp.post(this)
//                .api(new UpdateImageApi()
//                        .setImage(file))
//                .request(new HttpCallback<HttpData<String>>(this) {
//
//                    @Override
//                    public void onSucceed(HttpData<String> data) {
//                        mAvatarUrl = Uri.parse(data.getData());
//                        GlideApp.with(getActivity())
//                                .load(mAvatarUrl)
//                                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
//                                .into(mAvatarView);
//                        if (deleteFile) {
//                            file.delete();
//                        }
//                    }
//                });
    }
}